using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Domain.SalesManage;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using RBAC.Read.Api.Application.Dto.ERP;
using Dapper;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 客户模糊查询处理器（返回Id与名称）
    /// </summary>
    public class SearchCustomerHandler : IRequestHandler<SearchCustomerCommand, APIResult<List<CustomerOptionDto>>>
    {
        private readonly IBaseRepository<Customer> _customerRepo;

        public SearchCustomerHandler(IBaseRepository<Customer> customerRepo)
        {
            _customerRepo = customerRepo;
        }

        public Task<APIResult<List<CustomerOptionDto>>> Handle(SearchCustomerCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var keyword = request.Keyword?.Trim();
                var top = request.Top <= 0 ? 20 : request.Top;
                if (top > 50) top = 50; // 最大限制，避免一次返回过多

                var sql = @"SELECT Id, CustomerName FROM Customer WHERE IsDeleted = FALSE";
                var param = new DynamicParameters();
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    sql += " AND CustomerName LIKE @kw";
                    param.Add("@kw", $"%{keyword}%");
                }
                sql += " ORDER BY Id DESC LIMIT @Top";
                param.Add("@Top", top);

                var list = _customerRepo.Query<CustomerOptionDto>(sql, param);

                return Task.FromResult(new APIResult<List<CustomerOptionDto>>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = list
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<List<CustomerOptionDto>>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询失败：" + ex.Message,
                    Data = new List<CustomerOptionDto>()
                });
            }
        }
    }
}
